package com.myappengine.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.myappengine.model.Person;

@Repository
public class PersonDAO {
	
	public void savePerson(Person person) {
		DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
		Entity entity = new Entity("Person");
		entity.setProperty("name", person.getName());
		entity.setProperty("age", person.getAge());
		entity.setProperty("address", person.getAddress());
		entity.setProperty("salary", person.getSalary());
		datastoreService.put(entity);
	}
	
	public List<Person> getAllPerson() throws Exception {
		DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("Person");
		PreparedQuery pq = datastoreService.prepare(query);
		List<Person> persons = new ArrayList<Person>();
		for (Entity p : pq.asIterable()) {
			System.out.println("This line is numbered as 34");
			String name = (String) p.getProperty("name");
			Long age = (Long) p.getProperty("age");
			String address = (String) p.getProperty("address");
			Double salary = (Double) p.getProperty("salary");
			Person s = new Person(name, age, address, salary);
			persons.add(s);
		}
		return persons;
	}
}
